<?php
declare (strict_types=1);

namespace app\shop_admin\service;

use app\shop_admin\model\ShopAssistant as admin;
use app\shop_admin\model\User;
use app\utils\TrimData;
use think\Exception;
use think\facade\Cache;

class ShopAssistantService
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $list = admin::field('id,user_id,store_id,serial_num')
            ->where('status', 1)
            ->with(['user', 'store'])
            ->select();
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = admin::field('id,user_id,store_id,serial_num,status,create_time,update_time')
            ->with(['user', 'store']);
        $admin = TrimData::searchDataTrim($admin, $data, ['serial_num']);

        $list = $admin->where($data)->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        $indexUser = User::find($data['user_id']);
        if (!$indexUser) {
            throw new Exception("用户不存在", HTTP_NOTACCEPT);
        }
        $is_exists= admin::where(['user_id'=>$indexUser->id,'store_id'=>$data['store_id']])->find();
        if ($is_exists){
            throw new Exception("该用户已是该店店员!", HTTP_NOTACCEPT);
        }
        $model = admin::create($data);
        $token = Cache::store('redis')->get("TOKEN:" . $data['user_id']);

        global $user;

        if (!empty($token)) {
            $tokenUser = Cache::store('redis')->get("INDEX:" . $token . "-" . $user->mall_id);
            if ($tokenUser) {
                $tokenUser = json_decode($tokenUser, true);
                $tokenUser['is_write'] = true;
                $tokenUser = json_encode($tokenUser);
                Cache::store('redis')->set("INDEX:" . $token . "-" . $user->mall_id, $tokenUser);
            }
        }
        return [HTTP_CREATED, $model];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::with(['user', 'store'])->find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {

        $update_time = $data['update_time'];
        unset($data['update_time']);

        $model = admin::where(['id'=>$id])->lock(true)->find($id);
        if (isset($data['user_id'])) {
            $indexUser = User::find($data['user_id']);
            if (!$indexUser) {
                throw new Exception("用户不存在", HTTP_NOTACCEPT);
            }
        }
        $is_exists= admin::where(['user_id'=>$indexUser->id,'store_id'=>$data['store_id']])->where('id','<>',$model->id)->find();
        if ($is_exists){
            throw new Exception("该用户已是该店店员!", HTTP_NOTACCEPT);
        }

        admin::where('update_time', $update_time)
            ->where('id', $id)
            ->save($data);

        global $user;

        if ($model->user_id !== $data['user_id']) {
            $existAssistant = admin::where(['user_id' => $model->user_id])->find();
            if (!$existAssistant) {
                $oldToken = Cache::store('redis')->get("TOKEN:" . $model->user_id);
                if (!empty($oldToken)) {
                    $oldUser = Cache::store('redis')->get("INDEX:" . $oldToken . "-" . $user->mall_id);
                    if($oldUser){
                        $oldUser = json_decode($oldUser, true);
                        $oldUser['is_write'] = false;
                        $oldUser = json_encode($oldUser);
                        Cache::store('redis')->set("INDEX:" . $oldToken . "-" . $user->mall_id, $oldUser);
                    }
                }
            }

        }

        $newToken = Cache::store('redis')->get("TOKEN:" . $data['user_id']);
        if (!empty($newToken)) {
            $newUser = Cache::store('redis')->get("INDEX:" . $newToken . "-" . $user->mall_id);
            if ($newUser) {
                $newUser = json_decode($newUser, true);
                $newUser['is_write'] = true;
                $newUser = json_encode($newUser);
                Cache::store('redis')->set("INDEX:" . $newToken . "-" . $user->mall_id, $newUser);
            }
        }

        return [HTTP_CREATED, 1];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        $data = admin::find($id);
        if (empty($data)){
            throw new Exception("店员不存在",HTTP_NOTACCEPT);
        }

        $data = $data->toArray();

        $token = Cache::store('redis')->get("TOKEN:" . $data['user_id']);
        global $user;

        if (!empty($token)) {
            $tokenUser = Cache::store('redis')->get("INDEX:" . $token . "-" . $user->mall_id);
            if ($tokenUser) {
                $tokenUser = json_decode($tokenUser, true);
                $tokenUser['is_write'] = false;
                $tokenUser = json_encode($tokenUser);
                Cache::store('redis')->set("INDEX:" . $token . "-" . $user->mall_id, $tokenUser);
            }
        }

        admin::destroy($id, true);
        return HTTP_NOCONTEND;
    }

}
